/**
 * @author Fatemeh Chegini 
 * @author Samuel Measho
 */
package myApp
import javax.servlet.http._
import javax.servlet.ServletConfig
import javax.servlet.ServletContext
import javax.servlet.http._
import javax.servlet.AsyncContext
import javax.servlet.ServletConfig
import scala.xml._
import scala.collection.JavaConversions._
import scala.util.matching.Regex
import scala.xml._
import org.squeryl.KeyedEntity
import org.squeryl.SessionFactory
import org.squeryl.Session
import org.squeryl.adapters.H2Adapter
import scala.xml.PrettyPrinter
import scala.xml.NodeSeq
import scala.xml.Elem
import org.squeryl.PrimitiveTypeMode._
import org.squeryl.dsl.ast.LogicalBoolean
import org.squeryl.annotations.OptionType
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.Queue
import java.util.concurrent.ConcurrentLinkedQueue
import org.scribe._
import org.scribe.builder._
import org.scribe.builder.api._
import org.scribe.model._
import org.scribe.oauth._
import myApp.routing._
import myApp.Template._
import scala.util.parsing.json.JSON
import java.net.URLEncoder
class MyApplication extends HttpServlet{

   type HandlerFunction = (HttpServletRequest, HttpServletResponse) => Unit
   /**
    * just to authenticate server to twitter
    */
   
   // print(response.getBody)
    val service = new ServiceBuilder().provider(classOf[TwitterApi]).apiKey("CHwrj5XscGzODGeuO7hgqw").apiSecret("h117oQvVlkksk8v7gWGx9D6FaJfNWAdAAC61UOpCcNI").build
   val accessToken = new Token("524524614-8WCQTA3tT4pBled77ATmEXdpHfOCcgJh1cTUYE8S", "yL0TE3nqmA2SNV5V6qi1SP1EmYbO9W4COF6h4jI5M8")
   
   
    val routing = new Routing()

    val template=new Template() 
    val allresult=""
    override def init(config: ServletConfig) {
	  super.init(config)
	 
	  	routing.addRoute("/", main)
	  	routing.addRoute("/mainCss.css", css)
	  	routing.addRoute("/poll", testing)
	  	routing.addRoute("/search.js", js)
	
	  
  }

   
  override def service(req: HttpServletRequest, resp: HttpServletResponse) {
    
	 //Routing dispatch
    if (routing.tableDispatch(req, resp))
      return
    resp.sendError(HttpServletResponse.SC_NOT_FOUND)

  }
  
  def urlEncode(in : String) = URLEncoder.encode(in, "UTF-8")
  def testing(req: HttpServletRequest, resp: HttpServletResponse){
    val searchString=req.getParameter("q")
   
    println("***********************")
    println(urlEncode(searchString))
    
   
    println("***********************")
    val request = new OAuthRequest(Verb.GET, "http://search.twitter.com/search.json?q="+urlEncode(searchString) +"&rpp=100&page=10")
    service.signRequest(accessToken, request)
    val response = request.send 
    val r1 = JSON.parseFull(response.getBody).get.asInstanceOf[Map[Any,List[Any]]]("results")
    val r = r1
    
    r1.foreach( x => 
   		  println(x.asInstanceOf[Map[Any,Any]]("to_user")+"\n")
   		)
  
   
   var a:Any=null 
   var ff:String="" 
   val div =
    	<div id="searching">
   			
   			
 					{
   				  		for (msg <- r1)
   				  			yield 
   				  				if(msg.asInstanceOf[Map[String,Any]]("profile_image_url_https")!=null)
   				  					{
   				  				  a=msg.asInstanceOf[Map[String,Any]]("profile_image_url_https")
   				  					ff=a.toString()
   				  						val  textresult=msg.asInstanceOf[Map[String,Any]]("text")
   				  					  println("########################")
   				  					  
   				  					  println(msg.asInstanceOf[Map[String,Any]]("profile_image_url_https"))
   				  					  println(msg.asInstanceOf[Map[String,Any]]("text").toString())
   				  					  println("########################")
   				  					  			
   				  					<div id="row">
   				  					  <div class='imagino'>
   				  					       <img id="personimage" border="0" src={{ff}} width="60" height="60" border-radius="15px"/>
                  		   			   </div>
   				  			<div class='tweetInfo'>
   				  					   <div class='userInfo'>
                  		  					<a href='http://twitter.com/intent/user?screen_name="+results[j]["from_user"]+"'>{msg.asInstanceOf[Map[String,Any]]("from_user_name")}</a>
   				  					   </div>
   				  					   <div class='textInfo'>
                  		  					{msg.asInstanceOf[Map[String,Any]]("text")}
                  		  			   </div>	
                  		  		     </div>
                  		  </div>
                  		  			
   				  					}
   				  		
   				  }
    
   		  
   		  

   	  </div>

     if (searchString.length()==0){
    resp.setContentType("text/html")
    resp.setStatus(HttpServletResponse.SC_OK)
    resp.getWriter.write(new PrettyPrinter(72, 2).formatNodes(<div id="searching"><div id = "table"><div>fatima</div></div></div>)) }
     else{
       
       resp.setContentType("text/html")
       resp.setStatus(HttpServletResponse.SC_OK)
       resp.getWriter.write(new PrettyPrinter(72, 2).formatNodes(div))
       
     }
    
      
      
  }
  
def main(req: HttpServletRequest, resp: HttpServletResponse) = {
   
    val xml = index
    resp.getWriter.write(new PrettyPrinter(72, 2).formatNodes(xml))
  }

 def css(req: HttpServletRequest, resp: HttpServletResponse) {
    
    val css = template.loadCss("mainCss.css")
    resp.getWriter.write(css)
    resp.setContentType("text/css")
    
  }
def js(req: HttpServletRequest, resp: HttpServletResponse) {
    
    val js = template.loadJs("search.js")
    resp.getWriter.write(js)
    resp.setContentType("text/css")
    
  }
 
def index={
  
 
	 val js="""
	   var _timer;
			 function updateMessages(xml) {
			 	$("div#results").html(xml);
			 }
      
			 function poll() {
			 	$.get("/poll", {message:"fatima"},function (x) { updateMessages(x); });
			 }
	   
			 function delaytorequest(){
	   
	   
			  clearTimeout(_timer);
			 _timer=setTimeout(function() {tweetSearch();},1250)
			 	//setInterval("tweetSearch()",1000)
			 	
			 }
	   
	   
	   
			 function tweetSearch() {
					
			 		
	  
	   
					var searchString = $("#x").attr("value");
			 		console.log(encodeURIComponent(searchString))
					console.log(searchString)
					$.ajax({
						type: "GET",
						url:"/poll?q="+encodeURIComponent(searchString), 
						dataType:"html",
						success:function(x){
							updateMessages(x) 
						},
			 			timeout: 30000
						
					})
	   
				}
	   
			 $(document).ready(function() {
			 	$("form#search").submit(function () {
			 		var msg = $("input#search").val();
			 		if(msg.length!=0){
			 			$("label#sent").html("search for  " + msg);
			 			$("input#search").val("");
			 			$.get("/poll", { message: msg },function (x) { updateMessages(x); });
			 			return false;
			 	}else{
			 		$("div#results").html("<p>please</p>");}
			 });
			 });
	   
			 $(document).ready(function() {
			 	
			 });
	   """ 
  
	 val css="""
	  
	   
	   """
<!---->
<html>
	 <head>
	 	<title>Home</title>
	 	<link rel="stylesheet" type="text/css" href="mainCss.css" />
	 	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"/>
 		<script type="text/javascript">{ new Unparsed(js) /* use Unparsed to avoid escaping " to &quot; */ }</script>
	 	<style type="text/css">{ new Unparsed(css) }</style>
	 	<script type="text/javascript" src="search.js"></script>
    </head>
	<body>		
	 	
	 	<header id="mainhead">
			<div id="title">
	 			<div style="height:100px; float:left; width:100px;">
	 				<img id="myImage" src="http://blog.mindjet.de/wp-content/uploads/2008/07/social_network_id469214_size440.jpg"  alt="myImage"/>
	 			</div>
	 			
	 		</div>


	 	<div id="headSearch" style="width:600px; margin-left:300px;margin-top:25px">
	 		<div style="width:600px; float:left;margin-left:300px;">
	 			<form id="search" action="">
          			<div style="width:326px; float:left margin-left:700px;">
            			<label for="message" style="color:white;">Search for:</label>
            			<input type="text" name="search" id="x" class="searchinput" onkeyup="delaytorequest()"/>
            			<label for="message" id="sent"/>
            		</div>
	 				
	 				
        		</form>
        	
	 		</div>
	 	</div>
	 	</header>
	 	
	 	
	 	
	
	 		
	 			<article id="article"></article>
	 			<aside id = "aside"><div id="results"/> </aside>
	 	
	 	
	 	 <footer >
         <p id="par">
		  Copyright Fatemeh Chegini - Samuel Measho - Last Updated: 30.04.2012
	     </p>
        </footer>

	 </body>
</html>
}
/**
 * <div style="width:80px; margin-left:5px; float:left">
            			<input type="submit" name="submit" id="submit" value="Search"/>
	 				</div>
 */




}

